/**
 * 单词本管理模块
 * 负责单词本的加载、管理和操作
 */

class WordbookManager {
    constructor() {
        this.wordbooks = [];
        this.builtinWordbooks = [];
        this.customWordbooks = [];
        this.MAX_WORDS_PER_BOOK = 8000; // 单词本容量上限
        this.isReady = false;
        
        console.log('📚 创建单词本管理器实例...');
    }

    async init() {
        console.log('📚 初始化单词本管理器...');
        
        try {
            // 加载内置单词本
            await this.loadBuiltinWordbooks();
            
            // 加载自定义单词本
            this.loadCustomWordbooks();
            
            // 合并所有单词本
            this.wordbooks = [...this.builtinWordbooks, ...this.customWordbooks];
            
            this.isReady = true;
            console.log(`✅ 加载了 ${this.wordbooks.length} 个单词本`);
            
            // 通知 app 更新界面
            if (window.app) {
                window.app.updateHomePage();
            }
            
            return true;
        } catch (error) {
            console.error('❌ 单词本加载失败:', error);
            this.isReady = false;
            return false;
        }
    }

    /**
     * 加载内置单词本
     */
    async loadBuiltinWordbooks() {
        console.log('📖 开始加载内置单词本...');
        console.log('检查 window.BUILTIN_WORDBOOKS_DATA:', !!window.BUILTIN_WORDBOOKS_DATA);
        
        // 优先使用内嵌数据（避免 fetch 跨域问题）
        if (window.BUILTIN_WORDBOOKS_DATA) {
            console.log('✅ 使用内嵌单词本数据');
            
            Object.keys(window.BUILTIN_WORDBOOKS_DATA).forEach(id => {
                const data = window.BUILTIN_WORDBOOKS_DATA[id];
                console.log(`  加载: ${data.name} (${data.words.length}词)`);
                
                const wordbook = {
                    id: id,
                    name: data.name,
                    type: 'builtin',
                    category: data.category,
                    description: data.description,
                    wordCount: data.words.length,
                    words: data.words,
                    createdAt: new Date().toISOString(),
                    stats: {
                        totalStudied: 0,
                        averageAccuracy: 0,
                        lastStudyDate: null
                    }
                };
                this.builtinWordbooks.push(wordbook);
            });
            
            console.log(`✅ 成功加载 ${this.builtinWordbooks.length} 个内置单词本`);
            return;
        }

        // 降级方案：尝试从 CSV 文件加载
        console.log('尝试从 CSV 文件加载单词本...');
        const builtinFiles = [
            { id: 'android-dev-common', path: 'data/android-dev-common.csv' },
            { id: 'typescript-dev-common', path: 'data/typescript-dev-common.csv' }
        ];

        for (const file of builtinFiles) {
            try {
                const wordbook = await this.loadCSV(file.path, file.id, 'builtin');
                if (wordbook) {
                    this.builtinWordbooks.push(wordbook);
                }
            } catch (error) {
                console.error(`加载内置单词本失败: ${file.path}`, error);
            }
        }
    }

    /**
     * 加载自定义单词本
     */
    loadCustomWordbooks() {
        const custom = storageManager.get(storageManager.keys.CUSTOM_WORDBOOKS) || [];
        this.customWordbooks = custom;
    }

    /**
     * 加载 CSV 文件
     */
    async loadCSV(path, id, type = 'builtin') {
        try {
            const response = await fetch(path);
            const text = await response.text();
            
            const { metadata, words } = this.parseCSV(text);
            
            return {
                id: id,
                name: metadata.name || path.split('/').pop().replace('.csv', ''),
                type: type,
                category: metadata.category || '编程开发',
                description: metadata.description || '',
                wordCount: words.length,
                words: words,
                createdAt: new Date().toISOString(),
                stats: {
                    totalStudied: 0,
                    averageAccuracy: 0,
                    lastStudyDate: null
                }
            };
        } catch (error) {
            console.error('加载 CSV 失败:', error);
            return null;
        }
    }

    /**
     * 解析 CSV 内容
     */
    parseCSV(text) {
        const lines = text.split('\n').filter(line => line.trim());
        const metadata = {};
        const dataLines = [];

        // 提取元数据和数据行
        lines.forEach(line => {
            if (line.startsWith('#')) {
                const match = line.match(/#\s*([^:]+):\s*(.+)/);
                if (match) {
                    const key = match[1].trim().toLowerCase().replace(/\s+/g, '');
                    metadata[key] = match[2].trim();
                }
            } else {
                dataLines.push(line);
            }
        });

        // 解析表头
        if (dataLines.length === 0) {
            throw new Error('CSV 文件为空');
        }

        const headers = dataLines[0].split(',').map(h => h.trim());
        
        // 验证必需字段
        if (!headers.includes('word')) {
            throw new Error('CSV 文件必须包含 "word" 字段');
        }

        // 解析数据
        const words = [];
        for (let i = 1; i < dataLines.length; i++) {
            const values = this.parseCSVLine(dataLines[i]);
            const word = {};

            headers.forEach((header, index) => {
                word[header] = values[index]?.trim() || '';
            });

            // 验证必需字段
            if (word.word) {
                words.push(word);
            }
        }

        return { metadata, words };
    }

    /**
     * 解析 CSV 行（处理引号内的逗号）
     */
    parseCSVLine(line) {
        const result = [];
        let current = '';
        let inQuotes = false;

        for (let i = 0; i < line.length; i++) {
            const char = line[i];

            if (char === '"') {
                inQuotes = !inQuotes;
            } else if (char === ',' && !inQuotes) {
                result.push(current);
                current = '';
            } else {
                current += char;
            }
        }

        result.push(current);
        return result;
    }

    /**
     * 获取所有单词本
     */
    getAllWordbooks() {
        return this.wordbooks;
    }

    /**
     * 根据 ID 获取单词本
     */
    getWordbookById(id) {
        return this.wordbooks.find(wb => wb.id === id);
    }

    /**
     * 获取总词汇量
     */
    getTotalWordsCount() {
        return this.wordbooks.reduce((sum, wb) => sum + wb.wordCount, 0);
    }

    /**
     * 验证单词本容量
     */
    validateWordbook(words) {
        if (words.length > this.MAX_WORDS_PER_BOOK) {
            return {
                valid: false,
                error: `单词本超过容量上限！当前 ${words.length} 个，最大支持 ${this.MAX_WORDS_PER_BOOK} 个。`,
                suggestion: '建议将单词本拆分为多个较小的单词本。'
            };
        }

        return { valid: true };
    }

    /**
     * 添加自定义单词本
     */
    addCustomWordbook(name, words) {
        // 验证容量
        const validation = this.validateWordbook(words);
        if (!validation.valid) {
            alert(validation.error + '\n\n' + validation.suggestion);
            return null;
        }

        const wordbook = {
            id: `custom-${Date.now()}`,
            name: name,
            type: 'custom',
            category: '自定义',
            description: '用户上传',
            wordCount: words.length,
            words: words,
            createdAt: new Date().toISOString(),
            stats: {
                totalStudied: 0,
                averageAccuracy: 0,
                lastStudyDate: null
            }
        };

        this.customWordbooks.push(wordbook);
        this.wordbooks.push(wordbook);
        
        this.saveCustomWordbooks();
        
        return wordbook;
    }

    /**
     * 删除自定义单词本（不带确认）
     */
    deleteWordbook(id) {
        const wordbook = this.getWordbookById(id);
        
        // 只能删除自定义单词本
        if (!wordbook || wordbook.type !== 'custom') {
            console.error('只能删除自定义单词本');
            return false;
        }

        this.customWordbooks = this.customWordbooks.filter(wb => wb.id !== id);
        this.wordbooks = this.wordbooks.filter(wb => wb.id !== id);
        
        this.saveCustomWordbooks();
        
        return true;
    }

    /**
     * 保存自定义单词本
     */
    saveCustomWordbooks() {
        storageManager.set(storageManager.keys.CUSTOM_WORDBOOKS, this.customWordbooks);
    }

    /**
     * 合并多个单词本（去重）
     */
    mergeWordbooks(wordbookIds) {
        const allWords = [];
        const wordMap = new Map();

        wordbookIds.forEach(id => {
            const wb = this.getWordbookById(id);
            if (wb) {
                wb.words.forEach(word => {
                    // 使用 word.word 作为唯一标识去重
                    if (!wordMap.has(word.word)) {
                        wordMap.set(word.word, {
                            ...word,
                            wordbookId: id,
                            wordbookName: wb.name
                        });
                    }
                });
            }
        });

        return Array.from(wordMap.values());
    }

    /**
     * 随机抽取单词
     */
    randomSelect(wordbookIds, count, strategy = 'random') {
        const allWords = this.mergeWordbooks(wordbookIds);
        
        // 根据策略选择
        let selectedWords = [];
        
        switch (strategy) {
            case 'random':
                selectedWords = this.randomSelectStrategy(allWords, count);
                break;
            case 'wrong':
                // TODO: 优先错词策略
                selectedWords = this.randomSelectStrategy(allWords, count);
                break;
            case 'difficult':
                // TODO: 优先难词策略
                selectedWords = this.randomSelectStrategy(allWords, count);
                break;
            case 'smart':
                // TODO: 智能推荐策略
                selectedWords = this.randomSelectStrategy(allWords, count);
                break;
            default:
                selectedWords = this.randomSelectStrategy(allWords, count);
        }

        return selectedWords;
    }

    /**
     * 完全随机策略
     */
    randomSelectStrategy(words, count) {
        const shuffled = [...words].sort(() => Math.random() - 0.5);
        return shuffled.slice(0, Math.min(count, words.length));
    }

    /**
     * 处理文件上传
     */
    async handleFileUpload(file) {
        if (!file || !file.name.endsWith('.csv')) {
            alert('请上传 CSV 格式的文件！');
            return false;
        }

        const reader = new FileReader();
        
        return new Promise((resolve, reject) => {
            reader.onload = async (e) => {
                try {
                    const text = e.target.result;
                    const { metadata, words } = this.parseCSV(text);
                    
                    // 验证容量
                    const validation = this.validateWordbook(words);
                    if (!validation.valid) {
                        alert(validation.error + '\n\n' + validation.suggestion);
                        reject(new Error(validation.error));
                        return;
                    }

                    // 提示用户输入单词本名称
                    const defaultName = metadata.wordbookname || 
                                       metadata.name || 
                                       file.name.replace('.csv', '');
                    
                    const name = prompt('请输入单词本名称:', defaultName);
                    if (!name) {
                        reject(new Error('用户取消'));
                        return;
                    }

                    // 添加单词本
                    const wordbook = this.addCustomWordbook(name, words);
                    if (wordbook) {
                        alert(`成功导入 ${words.length} 个单词！`);
                        resolve(wordbook);
                    } else {
                        reject(new Error('导入失败'));
                    }
                } catch (error) {
                    alert('文件解析失败：' + error.message);
                    reject(error);
                }
            };

            reader.onerror = () => {
                alert('文件读取失败！');
                reject(new Error('文件读取失败'));
            };

            reader.readAsText(file, 'UTF-8');
        });
    }

    /**
     * 初始化上传功能
     */
    initUpload() {
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const modal = document.getElementById('modal-upload');

        if (!uploadArea || !fileInput) return;

        // 点击上传区域
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        // 文件选择
        fileInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (file) {
                try {
                    await this.handleFileUpload(file);
                    
                    // 关闭模态框
                    modal.classList.remove('active');
                    
                    // 刷新所有相关界面
                    this.refreshAllPages();
                    
                    // 清空文件输入
                    fileInput.value = '';
                } catch (error) {
                    console.error('上传失败:', error);
                }
            }
        });

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = 'var(--primary-color)';
            uploadArea.style.background = 'var(--gray-50)';
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '';
            uploadArea.style.background = '';
        });

        uploadArea.addEventListener('drop', async (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '';
            uploadArea.style.background = '';

            const file = e.dataTransfer.files[0];
            if (file) {
                try {
                    await this.handleFileUpload(file);
                    modal.classList.remove('active');
                    this.refreshAllPages();
                } catch (error) {
                    console.error('上传失败:', error);
                }
            }
        });

        console.log('✅ 上传功能已初始化');
    }

    /**
     * 刷新所有相关页面
     */
    refreshAllPages() {
        // 刷新首页
        if (window.app) {
            app.updateHomePage();
            
            // 如果当前在单词本管理页面，刷新该页面
            if (app.currentPage === 'wordbooks') {
                this.renderWordbookManagePage();
            }
        }
    }

    /**
     * 初始化单词本选择界面
     */
    initWordbookSelection() {
        this.selectedWordbooks = new Set();
        this.renderWordbookSelection();
        this.bindSelectionEvents();
    }

    /**
     * 渲染单词本选择列表
     */
    renderWordbookSelection() {
        const container = document.getElementById('wordbook-selection');
        if (!container) return;

        const wordbooks = this.getAllWordbooks();
        
        if (wordbooks.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📚</div>
                    <h3>还没有单词本</h3>
                    <p>请先上传或创建单词本</p>
                </div>
            `;
            return;
        }

        // 按类型分组
        const builtin = wordbooks.filter(wb => wb.type === 'builtin');
        const custom = wordbooks.filter(wb => wb.type === 'custom');

        let html = '';

        // 内置单词本（可折叠）
        if (builtin.length > 0) {
            html += `
                <div class="collapsible-section">
                    <div class="section-header" onclick="wordbookManager.toggleSelectionSection('builtin-select')">
                        <h3 class="section-title-collapsible">
                            <span class="collapse-icon" id="icon-builtin-select">▼</span>
                            内置单词本
                            <span class="section-count">(${builtin.length})</span>
                        </h3>
                    </div>
                    <div class="section-content-selection" id="section-builtin-select">
                        ${builtin.map(wb => this.renderWordbookSelectionItem(wb)).join('')}
                    </div>
                </div>
            `;
        }

        // 自定义单词本（可折叠）
        if (custom.length > 0) {
            html += `
                <div class="collapsible-section">
                    <div class="section-header" onclick="wordbookManager.toggleSelectionSection('custom-select')">
                        <h3 class="section-title-collapsible">
                            <span class="collapse-icon" id="icon-custom-select">▼</span>
                            我的单词本
                            <span class="section-count">(${custom.length})</span>
                        </h3>
                    </div>
                    <div class="section-content-selection" id="section-custom-select">
                        ${custom.map(wb => this.renderWordbookSelectionItem(wb)).join('')}
                    </div>
                </div>
            `;
        }

        container.innerHTML = html;
        
        // 恢复选择页面的折叠状态
        this.restoreSelectionCollapseState();
    }

    /**
     * 切换选择页面的分组展开/折叠
     */
    toggleSelectionSection(sectionId) {
        const content = document.getElementById(`section-${sectionId}`);
        const icon = document.getElementById(`icon-${sectionId}`);
        
        if (!content || !icon) return;

        const isCollapsed = content.style.display === 'none';
        
        if (isCollapsed) {
            // 展开
            content.style.display = 'flex';
            icon.textContent = '▼';
            this.saveSelectionCollapseState(sectionId, false);
        } else {
            // 折叠
            content.style.display = 'none';
            icon.textContent = '▶';
            this.saveSelectionCollapseState(sectionId, true);
        }
    }

    /**
     * 保存选择页面的折叠状态
     */
    saveSelectionCollapseState(sectionId, collapsed) {
        const state = JSON.parse(localStorage.getItem('selectionCollapseState') || '{}');
        state[sectionId] = collapsed;
        localStorage.setItem('selectionCollapseState', JSON.stringify(state));
    }

    /**
     * 恢复选择页面的折叠状态
     */
    restoreSelectionCollapseState() {
        const state = JSON.parse(localStorage.getItem('selectionCollapseState') || '{}');
        
        Object.keys(state).forEach(sectionId => {
            if (state[sectionId]) {
                const content = document.getElementById(`section-${sectionId}`);
                const icon = document.getElementById(`icon-${sectionId}`);
                
                if (content && icon) {
                    content.style.display = 'none';
                    icon.textContent = '▶';
                }
            }
        });
    }

    /**
     * 渲染单词本选择项
     */
    renderWordbookSelectionItem(wordbook) {
        const isSelected = this.selectedWordbooks.has(wordbook.id);
        return `
            <label class="wordbook-selection-item ${isSelected ? 'selected' : ''}">
                <input type="checkbox" 
                       class="wordbook-checkbox" 
                       data-id="${wordbook.id}" 
                       ${isSelected ? 'checked' : ''}>
                <div class="selection-item-content">
                    <h4>${wordbook.name}</h4>
                    <p>${wordbook.wordCount} 个单词 · ${wordbook.category}</p>
                </div>
            </label>
        `;
    }

    /**
     * 绑定选择事件
     */
    bindSelectionEvents() {
        const container = document.getElementById('wordbook-selection');
        if (!container) return;

        container.addEventListener('change', (e) => {
            if (e.target.classList.contains('wordbook-checkbox')) {
                const id = e.target.dataset.id;
                if (e.target.checked) {
                    this.selectedWordbooks.add(id);
                } else {
                    this.selectedWordbooks.delete(id);
                }
                this.updateSelectionSummary();
            }
        });

        // 清空选择
        const clearBtn = document.getElementById('btn-clear-selection');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                this.selectedWordbooks.clear();
                this.renderWordbookSelection();
                this.updateSelectionSummary();
            });
        }

        // 快速选择数量
        const countTags = document.querySelectorAll('[data-count]');
        countTags.forEach(tag => {
            tag.addEventListener('click', () => {
                const count = tag.dataset.count;
                const input = document.getElementById('select-count');
                if (input) {
                    if (count === 'all') {
                        const totalWords = this.getTotalSelectedWords();
                        input.value = totalWords;
                    } else {
                        input.value = count;
                    }
                }
                // 更新按钮状态
                countTags.forEach(t => t.classList.remove('active'));
                tag.classList.add('active');
            });
        });
    }

    /**
     * 更新选择摘要
     */
    updateSelectionSummary() {
        const count = this.selectedWordbooks.size;
        const totalWords = this.getTotalSelectedWords();

        document.getElementById('selected-count').textContent = count;
        document.getElementById('selected-total-words').textContent = totalWords;
    }

    /**
     * 获取选中单词本的总词汇量
     */
    getTotalSelectedWords() {
        const ids = Array.from(this.selectedWordbooks);
        const words = this.mergeWordbooks(ids);
        return words.length;
    }

    /**
     * 渲染单词本管理页面
     */
    renderWordbookManagePage(filter = 'all') {
        const container = document.getElementById('wordbook-list');
        if (!container) return;

        let wordbooks = this.getAllWordbooks();

        // 按过滤条件筛选
        if (filter === 'builtin') {
            wordbooks = wordbooks.filter(wb => wb.type === 'builtin');
        } else if (filter === 'custom') {
            wordbooks = wordbooks.filter(wb => wb.type === 'custom');
        }

        if (wordbooks.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📚</div>
                    <h3>暂无${filter === 'custom' ? '自定义' : ''}单词本</h3>
                    <p>${filter === 'custom' ? '点击上方"+ 上传单词本"创建你的第一个单词本' : '单词本加载中...'}</p>
                </div>
            `;
            return;
        }

        // 按类型分组
        const builtin = wordbooks.filter(wb => wb.type === 'builtin');
        const custom = wordbooks.filter(wb => wb.type === 'custom');

        let html = '';

        // 内置单词本（可折叠）
        if (builtin.length > 0 && filter === 'all') {
            html += `
                <div class="collapsible-section">
                    <div class="section-header" onclick="wordbookManager.toggleSection('builtin')">
                        <h3 class="section-title-collapsible">
                            <span class="collapse-icon" id="icon-builtin">▼</span>
                            内置单词本
                            <span class="section-count">(${builtin.length})</span>
                        </h3>
                    </div>
                    <div class="section-content" id="section-builtin">
                        ${builtin.map(wb => this.renderWordbookManageItem(wb)).join('')}
                    </div>
                </div>
            `;
        } else if (builtin.length > 0) {
            html += '<h3 class="section-title">内置单词本</h3>';
            html += '<div class="wordbook-manage-list">';
            html += builtin.map(wb => this.renderWordbookManageItem(wb)).join('');
            html += '</div>';
        }

        // 自定义单词本（可折叠）
        if (custom.length > 0 && filter === 'all') {
            html += `
                <div class="collapsible-section">
                    <div class="section-header" onclick="wordbookManager.toggleSection('custom')">
                        <h3 class="section-title-collapsible">
                            <span class="collapse-icon" id="icon-custom">▼</span>
                            我的单词本
                            <span class="section-count">(${custom.length})</span>
                        </h3>
                    </div>
                    <div class="section-content" id="section-custom">
                        ${custom.map(wb => this.renderWordbookManageItem(wb)).join('')}
                    </div>
                </div>
            `;
        } else if (custom.length > 0) {
            html += '<h3 class="section-title">我的单词本</h3>';
            html += '<div class="wordbook-manage-list">';
            html += custom.map(wb => this.renderWordbookManageItem(wb)).join('');
            html += '</div>';
        }

        container.innerHTML = html;

        // 绑定操作按钮事件
        this.bindWordbookActions();
        
        // 恢复折叠状态
        this.restoreCollapseState();
    }

    /**
     * 切换分组展开/折叠
     */
    toggleSection(sectionId) {
        const content = document.getElementById(`section-${sectionId}`);
        const icon = document.getElementById(`icon-${sectionId}`);
        
        if (!content || !icon) return;

        const isCollapsed = content.style.display === 'none';
        
        if (isCollapsed) {
            // 展开
            content.style.display = 'flex';
            icon.textContent = '▼';
            this.saveCollapseState(sectionId, false);
        } else {
            // 折叠
            content.style.display = 'none';
            icon.textContent = '▶';
            this.saveCollapseState(sectionId, true);
        }
    }

    /**
     * 保存折叠状态
     */
    saveCollapseState(sectionId, collapsed) {
        const state = JSON.parse(localStorage.getItem('wordbookCollapseState') || '{}');
        state[sectionId] = collapsed;
        localStorage.setItem('wordbookCollapseState', JSON.stringify(state));
    }

    /**
     * 恢复折叠状态
     */
    restoreCollapseState() {
        const state = JSON.parse(localStorage.getItem('wordbookCollapseState') || '{}');
        
        Object.keys(state).forEach(sectionId => {
            if (state[sectionId]) {
                const content = document.getElementById(`section-${sectionId}`);
                const icon = document.getElementById(`icon-${sectionId}`);
                
                if (content && icon) {
                    content.style.display = 'none';
                    icon.textContent = '▶';
                }
            }
        });
    }

    /**
     * 渲染单词本管理项
     */
    renderWordbookManageItem(wordbook) {
        const progress = this.calculateProgress(wordbook);
        const canDelete = wordbook.type === 'custom';

        return `
            <div class="wordbook-manage-item" data-id="${wordbook.id}">
                <div class="wordbook-manage-header">
                    <div class="wordbook-manage-title">
                        <h3>${wordbook.name}</h3>
                        <span class="wordbook-type-badge ${wordbook.type}">${wordbook.type === 'builtin' ? '内置' : '自定义'}</span>
                    </div>
                    <div class="wordbook-manage-actions">
                        <button class="btn btn-sm btn-secondary" onclick="wordbookDetailManager.showDetail('${wordbook.id}')">
                            📄 查看详情
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="app.startStudy('${wordbook.id}')">
                            📖 开始学习
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="wordbookManager.exportWordbook('${wordbook.id}')">
                            💾 导出
                        </button>
                        ${canDelete ? `
                            <button class="btn btn-sm btn-danger" onclick="wordbookManager.deleteWordbookConfirm('${wordbook.id}')">
                                🗑️ 删除
                            </button>
                        ` : ''}
                    </div>
                </div>

                <div class="wordbook-manage-info">
                    <div class="info-row">
                        <span class="info-item">
                            <span class="info-icon">📝</span>
                            <span>${wordbook.wordCount} 个单词</span>
                        </span>
                        <span class="info-item">
                            <span class="info-icon">🏷️</span>
                            <span>${wordbook.category}</span>
                        </span>
                        ${wordbook.description ? `
                            <span class="info-item">
                                <span class="info-icon">📄</span>
                                <span>${wordbook.description}</span>
                            </span>
                        ` : ''}
                    </div>
                </div>

                <div class="wordbook-manage-stats">
                    <div class="stat-row">
                        <div class="stat-label">学习进度</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${progress}%"></div>
                        </div>
                        <div class="stat-value">${progress}%</div>
                    </div>
                    ${wordbook.stats.lastStudyDate ? `
                        <div class="stat-row">
                            <span class="stat-label">最后学习</span>
                            <span class="stat-value">${this.formatDate(wordbook.stats.lastStudyDate)}</span>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }

    /**
     * 计算学习进度
     */
    calculateProgress(wordbook) {
        if (!wordbook || !wordbook.words) {
            return 0;
        }

        // 获取背诵数据和听写数据
        const recitationData = storageManager.get(storageManager.keys.RECITATION_DATA) || {};
        const learningHistory = storageManager.get(storageManager.keys.LEARNING_HISTORY) || {};

        let masteredCount = 0;

        // 遍历单词本中的每个单词
        wordbook.words.forEach(word => {
            const wordKey = word.word;
            
            // 检查背诵数据
            const recitation = recitationData[wordKey];
            const dictation = learningHistory[wordKey];

            let isMastered = false;

            // 判断是否掌握（任一条件满足）
            // 1. 背诵模式：掌握度 >= 70分
            if (recitation && recitation.masteryScore >= 70) {
                isMastered = true;
            }

            // 2. 听写模式：正确率 >= 80% 且至少尝试3次
            if (dictation && dictation.attempts >= 3 && dictation.accuracy >= 0.8) {
                isMastered = true;
            }

            if (isMastered) {
                masteredCount++;
            }
        });

        // 计算百分比
        return Math.round((masteredCount / wordbook.wordCount) * 100);
    }

    /**
     * 更新单词本统计数据
     */
    updateWordbookStats(wordbookId) {
        const wordbook = this.getWordbookById(wordbookId);
        if (!wordbook) return;

        const recitationData = storageManager.get(storageManager.keys.RECITATION_DATA) || {};
        const learningHistory = storageManager.get(storageManager.keys.LEARNING_HISTORY) || {};

        let totalStudied = 0;
        let totalAccuracy = 0;
        let studiedCount = 0;

        wordbook.words.forEach(word => {
            const wordKey = word.word;
            
            // 统计学习过的单词
            const recitation = recitationData[wordKey];
            const dictation = learningHistory[wordKey];

            if (recitation && recitation.total > 0) {
                totalStudied++;
                studiedCount++;
                totalAccuracy += recitation.masteryScore / 100;
            } else if (dictation && dictation.attempts > 0) {
                totalStudied++;
                studiedCount++;
                totalAccuracy += dictation.accuracy;
            }
        });

        // 更新统计
        wordbook.stats.totalStudied = totalStudied;
        wordbook.stats.averageAccuracy = studiedCount > 0 ? Math.round((totalAccuracy / studiedCount) * 100) : 0;

        // 保存（如果是自定义单词本）
        if (wordbook.type === 'custom') {
            this.saveCustomWordbooks();
        }
    }

    /**
     * 格式化日期
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays === 0) {
            return '今天';
        } else if (diffDays === 1) {
            return '昨天';
        } else if (diffDays < 7) {
            return `${diffDays}天前`;
        } else {
            return date.toLocaleDateString();
        }
    }

    /**
     * 绑定单词本操作事件
     */
    bindWordbookActions() {
        // 事件委托已在 HTML 中使用 onclick
        console.log('✅ 单词本操作事件已绑定');
    }

    /**
     * 删除单词本（带确认）
     */
    deleteWordbookConfirm(id) {
        const wordbook = this.getWordbookById(id);
        if (!wordbook) return;

        if (confirm(`确定要删除单词本"${wordbook.name}"吗？\n\n此操作不可恢复！`)) {
            const success = this.deleteWordbook(id);
            if (success) {
                // 刷新所有页面
                this.refreshAllPages();
                
                alert('删除成功！');
            }
        }
    }

    /**
     * 导出单词本为 CSV
     */
    exportWordbook(id) {
        const wordbook = this.getWordbookById(id);
        if (!wordbook) return;

        // 生成 CSV 内容
        const headers = ['word', 'translation', 'category', 'type', 'difficulty', 'frequency', 'languages', 'example_code', 'pronunciation_mode'];
        let csv = '# Wordbook Name: ' + wordbook.name + '\n';
        csv += '# Category: ' + (wordbook.category || '自定义') + '\n';
        csv += '# Total Words: ' + wordbook.wordCount + '\n';
        csv += '\n';
        csv += headers.join(',') + '\n';

        wordbook.words.forEach(word => {
            const row = headers.map(h => {
                const value = word[h] || '';
                // 如果包含逗号，用引号包裹
                return value.includes(',') ? `"${value}"` : value;
            });
            csv += row.join(',') + '\n';
        });

        // 下载文件
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${wordbook.name}-${Date.now()}.csv`;
        a.click();
        URL.revokeObjectURL(url);

        console.log('导出成功:', wordbook.name);
    }

    /**
     * 初始化单词本管理页面
     */
    initWordbookManagePage() {
        // 渲染列表
        this.renderWordbookManagePage();

        // 绑定标签切换
        const tabs = document.querySelectorAll('.tab-btn');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                const filter = tab.dataset.tab;
                this.renderWordbookManagePage(filter);
            });
        });

        console.log('✅ 单词本管理页面已初始化');
    }
}

// 全局实例
let wordbookManager;

// 等待 DOM 和 storage 准备好
document.addEventListener('DOMContentLoaded', async () => {
    // 确保 storageManager 已初始化
    if (window.storageManager) {
        wordbookManager = new WordbookManager();
        window.wordbookManager = wordbookManager;
        
        // 等待 init 完成
        await wordbookManager.init();
        
        // 初始化上传功能
        wordbookManager.initUpload();
        
        // 绑定上传按钮（多个页面可能有）
        const uploadBtns = document.querySelectorAll('#btn-upload-wordbook, #btn-upload-wordbook-page');
        uploadBtns.forEach(uploadBtn => {
            uploadBtn.addEventListener('click', () => {
                const modal = document.getElementById('modal-upload');
                if (modal) {
                    modal.classList.add('active');
                }
            });
        });

        // 绑定模态框关闭按钮
        const closeButtons = document.querySelectorAll('.btn-close');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const modalId = btn.dataset.modal;
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.classList.remove('active');
                }
            });
        });

        // 点击模态框背景关闭
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.remove('active');
                }
            });
        });
        
        console.log('✅ 单词本管理器完全就绪');
    }
});

